from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.database import get_db
from app.models.user import User
from app.models.schemas import UserResponse, UserUpdate
from app.routers.auth import get_current_active_user
from app.services.user_service import user_service
from app.middleware.response_formatter import format_success_response

router = APIRouter()


def is_super_admin(user: User) -> bool:
    """检查用户是否是超级管理员 (is_superuser = 1)"""
    return user.is_superuser == 1


def is_admin_or_super(user: User) -> bool:
    """检查用户是否是管理员（普通管理员或超级管理员）"""
    return user.is_superuser in [1, 2]


@router.get("/")
def get_users(
    page: int = Query(1, ge=1, description="当前页，从1开始"),
    pageSize: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """获取用户列表（分页）"""
    # 计算skip值
    skip = (page - 1) * pageSize
    limit = pageSize

    # 获取用户列表和总数
    if search:
        users = user_service.search_users(db, search=search, skip=skip, limit=limit)
        total = user_service.count_search_users(db, search=search)
    else:
        users = user_service.get_multi(db, skip=skip, limit=limit)
        total = user_service.count(db)

    # 转换为响应模型
    user_list = [UserResponse.from_orm(user) for user in users]

    # 返回符合要求的数据结构
    return format_success_response(
        data={
            "list": user_list,
            "page": page,
            "pageSize": pageSize,
            "total": total,
        },
        message="success",
    )


@router.get("/count")
def get_users_count(
    search: Optional[str] = Query(None, description="搜索关键词"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """获取用户总数"""
    if search:
        count = user_service.count_search_users(db, search=search)
    else:
        count = user_service.count(db)

    return {"count": count}


@router.get("/{user_id}", response_model=UserResponse)
def get_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """根据ID获取用户"""
    user = user_service.get(db, user_id)

    if user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

    return user


@router.put("/{user_id}", response_model=UserResponse)
def update_user(
    user_id: int,
    user_update: UserUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """更新用户信息"""
    # 检查是否是更新自己的信息或者是管理员
    if user_id != current_user.id and not is_admin_or_super(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="没有权限修改其他用户信息"
        )

    user = user_service.get(db, user_id)
    if user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

    try:
        # 更新用户信息
        updated_user = user_service.update(db, db_obj=user, obj_in=user_update)
        if updated_user is None:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="用户更新失败"
            )
        return updated_user
    except HTTPException:
        # 重新抛出HTTP异常（如唯一性验证错误）
        raise
    except Exception as e:
        # 捕获其他异常并记录
        print(f"ERROR - 用户更新异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="用户更新时发生错误",
        )


@router.delete("/{user_id}")
def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """删除用户（仅超级用户）"""
    if not is_super_admin(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="只有超级用户可以删除用户"
        )

    if user_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="不能删除自己"
        )

    user = user_service.get(db, user_id)
    if user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

    user_service.remove(db, id=user_id)
    return {"message": "用户删除成功"}


@router.patch("/{user_id}/toggle-active")
def toggle_user_active(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """切换用户启用/禁用状态（仅超级用户）"""
    if not is_super_admin(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="只有超级用户可以修改用户状态"
        )

    if user_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="不能修改自己的状态"
        )

    user = user_service.toggle_active(db, user_id=user_id)
    if user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

    status_text = "启用" if user.is_active else "禁用"
    return {"message": f"用户已{status_text}"}
